<template>
  <a-card :bordered="false">
    <detail-list title="基本信息">
      <detail-list-item term="活动名称">{{ info.name }}</detail-list-item>
      <detail-list-item term="活动编号">{{ info.numbering }}</detail-list-item>
      <detail-list-item term="状态">{{ statusMap[info.status] }}</detail-list-item>
      <detail-list-item term="商品名称">{{ info.commodity && info.commodity.name }}</detail-list-item>
      <detail-list-item term="商品编号">{{ info.commodity && info.commodity.numbering }}</detail-list-item>
      <detail-list-item term="商品主图">
        <a-row :gutter="[30, 30]">
          <a-col span="8" v-for="att in productMainPicture" :key="att.id">
            <img width="100px" :src="att.url"/>
          </a-col>
        </a-row>
      </detail-list-item>
      <detail-list-item term="详情文字">{{ info.desc }}</detail-list-item>
      <detail-list-item term="详情图片">
        <a-row :gutter="[30, 30]">
          <a-col span="8" v-for="att in detailPicture" :key="att.id">
            <img width="100px" :src="att.url"/>
          </a-col>
        </a-row>
      </detail-list-item>

      <a-table
        :columns="skuColumns"
        :data-source="skuData"
        :pagination="false"
        rowKey="id"
      >
        <template slot="stock" slot-scope="record">
          <editable-cell :text="parseInt(record.stock || 0)" @change="onSkuStockChange(record.id, 'stock', $event)"/>
        </template>
      </a-table>
    </detail-list>

    <a-divider/>

    <detail-list title="活动信息">
      <detail-list-item term="锁单">{{ lockingMap[info.locking] }}</detail-list-item>
      <detail-list-item term="总销量">{{ totalStock }}</detail-list-item>
      <detail-list-item term="抢购时间">{{ info.panic_buying_start_time }} 至 {{ info.panic_buying_end_time }}
      </detail-list-item>
      <detail-list-item term="邮费">{{ info.freight | formatAmount }}</detail-list-item>
      <detail-list-item term="包邮条件">{{ freightCondition }}</detail-list-item>
      <detail-list-item term="售后截止时间">{{ info.after_sale_deadline }}</detail-list-item>
      <detail-list-item term="预计发货时间">{{ info.estimated_delivery_time }}</detail-list-item>
      <detail-list-item term="同一地址限购数量">{{ info.address_purchase_restriction === 0 ? '无限制' :
        info.address_purchase_restriction }}
      </detail-list-item>
    </detail-list>
  </a-card>
</template>

<script>
  import { getCommodityActivityLiveTodayInfo, updateLiveTodaySku } from '@/api/commodity'
  import DetailList from '@/components/DescriptionList/DescriptionList'
  import EditableCell from '@/components/EditableCell/EditableCell'
  import pick from 'lodash.pick'
  import { formatAmount } from '@/utils/util'

  const DetailListItem = DetailList.Item

  const LOCKING_MAP = {
    1: '激活',
    2: '锁定'
  }

  const STATUS_MAP = {
    1: '已上架',
    2: '已下架'
  }

  export default {
    name: 'Info',
    components: { DetailList, DetailListItem, EditableCell },
    created () {
      // 这里好评返团用直播接口也没问题, 接口 id 通用的
      getCommodityActivityLiveTodayInfo(this.$route.params.id).then(res => {
        this.info = res

        // 整理 SKU 的表头
        this.info.attributes.reverse().forEach(attribute => this.skuColumns.unshift({
          'title': attribute.name,
          dataIndex: attribute.id
        }))
        // 整理 SKU 数据
        this.info.skus.reverse().forEach(sku => {
          // sku 系统字段
          const sysField = pick(
            sku,
            [ 'id', 'direct_invitation', 'elite_price', 'entry_price', 'external_guide_price',
              'group_owner_price', 'indirect_invitation', 'strongman_price', 'purchase_price', 'sales', 'stock'
              // 'estimated_sales' // 已废弃
            ]
          )
          // 格式化
          Object.keys(sysField).forEach(field => {
            if ([
              'id', 'stock', 'sales'
              // 'estimated_sales' // 已废弃
            ].includes(field)) {
              return
            }
            sysField[field] = formatAmount(sysField[field])
          })
          sysField.amount = sku.amount
          // sku 自定义数据
          sku.values.forEach(value => {
            sysField[value.attribute_id] = value.content
          })

          this.skuData.push(sysField)
        })
      })
    },
    computed: {
      totalStock () {
        if (!this.info.skus) {
          return 0
        }
        let totalSales = 0
        this.info.skus.forEach(sku => {
          totalSales += sku.sales
        })
        return totalSales
      },
      freightCondition () {
        const freeShippingConditions = []
        let tips = '包邮'
        if (this.info.free_shipping_maximum && this.info.free_shipping_maximum > 0) {
          freeShippingConditions.push(`小于${this.info.free_shipping_maximum}`)
        }
        if (this.info.free_shipping_minimal && this.info.free_shipping_minimal > 0) {
          freeShippingConditions.push(`大于等于${this.info.free_shipping_minimal}`)
        }
        if (freeShippingConditions.length > 0) {
          tips = freeShippingConditions.join(' ') + '件包邮' // 免邮条件
        }
        return tips
      },
      productMainPicture () {
        return this.info.attachments && this.info.attachments.filter(att => att.pivot.type === 1)
      },
      detailPicture () {
        return this.info.attachments && this.info.attachments.filter(att => att.pivot.type === 2)
      }
    },
    data () {
      return {
        info: {},
        statusMap: STATUS_MAP,
        lockingMap: LOCKING_MAP,
        skuColumns: [
          {
            title: '入仓价（元）',
            dataIndex: 'entry_price'
          },
          {
            title: '进价（元）',
            dataIndex: 'purchase_price'
          },
          {
            title: '大咖价（元）',
            dataIndex: 'strongman_price'
          },
          {
            title: '精英价（元）',
            dataIndex: 'elite_price'
          },
          {
            title: '群主价（元）',
            dataIndex: 'group_owner_price'
          },
          {
            title: '直接奖励（元）',
            dataIndex: 'direct_invitation'
          },
          {
            title: '间接奖励（元）',
            dataIndex: 'indirect_invitation'
          },
          {
            title: '对外价格（元）',
            dataIndex: 'external_guide_price'
          },
          {
            title: '发布量',
            customRender: (index, item) => {
              return parseInt((item.stock || 0)) + parseInt((item.sales || 0))
            }
          },
          {
            title: '销售量',
            customRender: (index, item) => {
              return parseInt(item.sales || 0)
            }
          },
          {
            title: '库存',
            scopedSlots: { customRender: 'stock' }
          }
          // {
          //   title: '预计销量', // 已废弃
          //   dataIndex: 'estimated_sales'
          // }
        ],
        skuData: []
      }
    },
    methods: {
      onSkuStockChange (id, dataIndex, value) {
        const dataSource = [...this.skuData]
        const target = dataSource.find(item => item.id === id)
        if (target) {
          // 这里好评返团用直播接口也没问题, sku id 通用的
          updateLiveTodaySku(id, { stock: value })
            .then(res => {
              this.$notification.success({ message: '操作成功!' })

              target[dataIndex] = value
            })
        }
      }
    }
  }
</script>

<style scoped>
</style>
